import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import { useSettingStore } from '@/store/setting'

// import.meta.glob 为 vite 提供的特殊导入方式
// 它可以将模块中全部内容导入并返回一个Record对象
// 默认为懒加载模式 加入配置项 eager 取消懒加载
const modules: Record<any, any> = import.meta.glob(['./modules/*.ts'], {
	eager: true,
	import: 'default'
})
const routes: Array<RouteRecordRaw> = []

Object.entries(modules).forEach(([, item]) => {
	routes.push(item)
})

const settingStore = useSettingStore()

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes
})
const routeList = router.getRoutes()

const breadcrumbCompose = (name: string, compose: string[]) => {
	const currentRoute = routeList.find((route) => route.name === name)
	const parentRoute = routeList.find((route) => route.name === currentRoute?.meta.parentRouter)

	if (parentRoute) {
		const parentName = parentRoute.name as string
		return breadcrumbCompose(parentName, [name, ...compose])
	}

	return [name, ...compose]
}

const breadcrumbHandler = (name: string) => {
	const breadcrumbArr = breadcrumbCompose(name, [])
	settingStore.setBreadcrumbArr(breadcrumbArr)
}

const whiteList = ['/login', '/about']
router.beforeEach(async (_to, _from, next) => {
	NProgress.start()
	const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
	const isLogin = userInfo && userInfo.accessToken
	if (isLogin || whiteList.includes(_to.path)) {
		next()
	} else {
		next('/login')
	}
	breadcrumbHandler(<string>_to.name)
})

router.afterEach((_to) => {
	NProgress.done()
})

export default router
